import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/a_elder/models/code_value_entity.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/model/update_file_model.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/widgets/bottom_input_widget.dart';
import 'package:ls_work/widgets/input_text_page.dart';

import '../../model/food_sample/food_sample_model.dart';
import '../../model/food_sample/food_sample_submit_data.dart';
import '../model/combo_data_model.dart';

class AddFoodSampleViewModel extends BaseViewModel {
  final String? id;
  final bool isChange;

  AddFoodSampleViewModel(BuildContext context, {this.id, this.isChange = false})
      : super(context);

  var model = FoodSampleModel();
  var submitData = FoodSampleSubmitData();
  var comboModel = ComboDataModel();
  var uploadModel = UploadFileModel();

  var format = [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ":", ss];

  Widget contentView() {
    return ListView(
      children: [
        Column(
          children: [
            IconTitleTextWidget(
              "留样时间：",
              isRequired: true,
              text: submitData.sampleDate??"",
              hintText: "请选择留样时间",
              arrow: Icon(Icons.keyboard_arrow_right),
              padding: EdgeInsets.zero,
              showArrow: isChange,
            ).onTap(() {
              if (!isChange) {
                return;
              }
              DatePicker.showDateTimePicker(context, onConfirm: (date) {
                submitData.sampleDate = date?.toDateStr(format);
                notifyListeners();
              },
                  currentTime: submitData.sampleDate.isNullOrEmpty()
                      ? null
                      : DateTime.parse(submitData.sampleDate??""));
            }),
            Gaps.dividerLine,
            IconTitleTextWidget(
              "留样编号：",
              isRequired: true,
              text: submitData?.sampleNo??"",
              hintText: "请输入留样编号",
              arrow: Icon(Icons.keyboard_arrow_right),
              padding: EdgeInsets.zero,
              showArrow: isChange,
            ).onTap(() {
              if (!isChange) {
                return;
              }
              showBottomInput(context,
                  title: "留样编号",
                  content: submitData.sampleNo ?? "", onSubmit: (str) {
                    submitData.sampleNo = str;
                    notifyListeners();
                  });
            }),
            Gaps.dividerLine,
            IconTitleTextWidget(
              "消毒时间：",
              isRequired: false,
              text: submitData.sterDate??"",
              hintText: "请选择消毒时间",
              arrow: Icon(Icons.keyboard_arrow_right),
              padding: EdgeInsets.zero,
              showArrow: isChange,
            ).onTap(() {
              if (!isChange) {
                return;
              }
              DatePicker.showDateTimePicker(context, onConfirm: (date) {
                submitData.sterDate = date?.toDateStr(format);
                notifyListeners();
              },
                  currentTime: submitData.sterDate.isNullOrEmpty()
                      ? null
                      : DateTime.parse(submitData.sterDate??""));
            }),
            Gaps.dividerLine,
            IconTitleTextWidget(
              "销毁时间：",
              isRequired: false,
              text: submitData.destroyedDate??"",
              hintText: "请选择销毁时间",
              arrow: Icon(Icons.keyboard_arrow_right),
              padding: EdgeInsets.zero,
              showArrow: isChange,
            ).onTap(() {
              if (!isChange) {
                return;
              }
              DatePicker.showDateTimePicker(context, onConfirm: (date) {
                submitData.destroyedDate = date?.toDateStr(format);
                notifyListeners();
              },
                  currentTime: submitData.destroyedDate.isNullOrEmpty()
                      ? null
                      : DateTime.parse(submitData.destroyedDate??""));
            }),
          ],
        ).addToContainer(
            color: Colors.white,
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10)),
        ...(submitData.details ?? []).map((sample) {
          return Column(
            children: [
              Container(
                height: 10,
                color: Colors.grey[100],
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      CommonText('食品样本').addToContainer(
                          padding: EdgeInsets.symmetric(vertical: 4)),
                      !isChange
                          ? Container()
                          : (submitData.details ?? []).length != 1
                          ? Icon(
                        Icons.remove_circle_outline,
                        color: Colors.red,
                      ).onTap(() {
                        submitData.details?.remove(sample);
                        notifyListeners();
                      })
                          : Container()
                    ],
                  ),
                  IconTitleTextWidget(
                    "标签号：",
                    isRequired: true,
                    text: sample.label??"",
                    hintText: "请输入标签号",
                    arrow: Icon(Icons.keyboard_arrow_right),
                    padding: EdgeInsets.zero,
                    showArrow: isChange,
                  ).onTap(() {
                    if (!isChange) {
                      return;
                    }
                    showBottomInput(context,
                        title: "标签号",
                        content: sample.label ?? "", onSubmit: (str) {
                          sample.label = str;
                          notifyListeners();
                        });
                  }),
                  Gaps.dividerLine,
                  IconTitleTextWidget(
                    "餐别：",
                    isRequired: true,
                    text: sample.categoryName??"",
                    hintText: "请选择餐别",
                    arrow: Icon(Icons.keyboard_arrow_right),
                    padding: EdgeInsets.zero,
                    showArrow: isChange,
                  ).onTap(() {
                    if (!isChange) {
                      return;
                    }
                    selectFoodTime((value) {
                      sample.categoryName = value.name;
                      sample.category = value.codeValue;
                      notifyListeners();
                    });
                  }),
                  Gaps.dividerLine,
                  IconTitleTextWidget(
                    "餐名：",
                    isRequired: true,
                    text: sample.foodName??"",
                    hintText: "请输入餐名",
                    arrow: Icon(Icons.keyboard_arrow_right),
                    padding: EdgeInsets.zero,
                    showArrow: isChange,
                  ).onTap(() {
                    if (!isChange) {
                      return;
                    }
                    showBottomInput(context,
                        title: "餐名",
                        content: sample.foodName ?? "", onSubmit: (str) {
                          sample.foodName = str;
                          notifyListeners();
                        });
                  }),
                  Gaps.dividerLine,
                  IconTitleTextWidget(
                    "留样量：",
                    isRequired: true,
                    text: sample.sampleVolume.isNullOrEmpty()
                        ? ""
                        : "${sample.sampleVolume}g",
                    hintText: "请输入留样量",
                    arrow: Icon(Icons.keyboard_arrow_right),
                    padding: EdgeInsets.zero,
                    showArrow: isChange,
                  ).onTap(() {
                    if (!isChange) {
                      return;
                    }
                    showBottomInput(context,
                        title: "留样量",
                        content: sample.sampleVolume ?? "",
                        keyboard: CommonInputType.numberAndDecimal,
                        onSubmit: (str) {
                          sample.sampleVolume = str;
                          notifyListeners();
                        });
                  }),
                  Gaps.dividerLine,
                  CommonText('照片').addToContainer(
                      padding: EdgeInsets.symmetric(vertical: 16)),
                  GridView.builder(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 4,
                        mainAxisSpacing: 10,
                        crossAxisSpacing: 10),
                    itemBuilder: (context, index) {
                      return (sample.attachList ?? []).isEmpty ||
                          index > (sample.attachList ?? []).length - 1
                          ? Icon(
                        Icons.add,
                        color: Colors.grey,
                      )
                          .addToContainer(
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey),
                          borderRadius: 5.borderRadius,
                        ),
                      )
                          .onTap(() {
                        chooseImageAndUpload(sample);
                      })
                          : Stack(
                        children: [
                          Hero(
                              tag:
                              "${HttpApi.imageHead}${sample.attachList![index]}",
                              child: ImageLoad(
                                "${HttpApi.imageHead}${sample
                                    .attachList![index]}",
                                fit: BoxFit.cover,
                              ).toRound(borderRadius: 5.borderRadius))
                              .onTap(() {
                            var images = sample.attachList!.map((e) => "${HttpApi
                                .imageHead}${e}").toList();
                            showBigImage(context, images,position: index);
                          })
                              .setLocation(
                              left: 0, right: 0, top: 0, bottom: 0),
                          if (isChange)
                            Icon(
                              Icons.remove_circle,
                              color: Colors.red,
                            ).onTap(() {
                              sample.attachList!.removeAt(index);
                              notifyListeners();
                            }).setLocation(right: 0, top: 0)
                        ],
                      );
                    },
                    itemCount:
                    (sample.attachList ?? []).length + (isChange ? 1 : 0),
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                  )
                ],
              ).addToContainer(
                  width: double.infinity,
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10))
            ],
          );
        }).toList(),
        if (isChange)
          ElevatedButton(
              onPressed: () {
                submitSample();
              },
              style: ButtonStyle(
                  shape: WidgetStateProperty.all(StadiumBorder()),
                  minimumSize: WidgetStateProperty.all(Size.fromHeight(45))
              ),
              child: CommonText('提交', textColor: Colors.white))
              .addToContainer(
              margin: EdgeInsets.symmetric(horizontal: 16, vertical: 18))
      ],
    );
  }

  @override
  void onCreated() {
    super.onCreated();
    if (id.isNullOrEmpty()) {
      _initData();
    } else {
      requestNetData();
    }
  }

  Future<void> requestNetData() async {
    await _requestFoodTime();
    await getDetailData();
  }

  Future<void> getDetailData() async {
    showLoadingState();
    try {
      var data = await model.sampleDetail(id);
      submitData = data.toSubmitData(foodTimeList);
      showContent();
    } catch (e) {
      print(e);
      showErrorState(NetErrorUtils.getNetError(e));
    }
  }

  void _initData() {
    if (submitData.details == null) {
      submitData.details = [FoodSampleSubmitDetail()];
      notifyListeners();
    }
  }

  var foodTimeList = <CodeValue>[];

  Future<void> selectFoodTime(Function(CodeValue value) listener) async {
    await _requestFoodTime();
    DataPickerView(context, foodTimeList, onSubmitListener: (p1, p2, p3) {
      listener(foodTimeList[p1]);
    }).show();
  }

  Future<void> _requestFoodTime() async {
    if (foodTimeList.isEmpty) {
      showLoadingDialog();
      try {
        foodTimeList = await comboModel.getComboData(ComboDataModel.foodTime);
        hideDialog();
      } catch (e) {
        showToast(NetErrorUtils.getNetError(e));
        hideDialog();
      }
    }
  }

  void chooseImageAndUpload(FoodSampleSubmitDetail sample) {
    uploadModel.showSelectCameraWithUpload(context, (data) {
      if (sample.attachList == null) {
        sample.attachList = [data.id!];
      } else {
        sample.attachList!.insert(0, data.id!);
      }
      notifyListeners();
    }, onStart: () {
      showLoadingDialog(msg: '提交中...');
    }, onEnd: () {
      hideDialog();
    }, onError: (error) {
      showToast(error);
    });
  }

  void addFoodSample() {
    submitData.details!.add(FoodSampleSubmitDetail());
    notifyListeners();
  }

  Future<void> submitSample() async {
    if (submitData.sampleDate.isNullOrEmpty()) {
      showToast("请选择留样时间");
      return;
    }
    if (submitData.sampleNo.isNullOrEmpty()) {
      showToast("请输入留样编号");
      return;
    }

    for (var food in (submitData.details??<FoodSampleSubmitDetail>[])) {
      if (food.label.isNullOrEmpty()) {
        showToast("请输入样本标签号");
        return;
      }
      if (food.category.isNullOrEmpty()) {
        showToast("请选择餐别");
        return;
      }
      if (food.foodName.isNullOrEmpty()) {
        showToast("请输入餐名");
        return;
      }
      if (food.sampleVolume.isNullOrEmpty()) {
        showToast("请输入留样量");
        return;
      }
    }

    showLoadingDialog(msg: '提交中...');
    try {
      var data = await model.submitSample(submitData);
      sendMessage(SendMessageEvent(MessageConfig.REFRESH_SAMPLE_LIST));
      hideDialog();
      finish();
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }
}
